/**
 * @brief 对象池分配器
 * @version 1.0.0
 * @author 宋炜
 */

#pragma once

#include <memory>
#include <type_traits>

#include "./objMemPool.hpp"
namespace wheels{
template< typename TYPE >
class objPoolAllocator : public std::allocator< TYPE >
{
public:
    using type_t = typename std::remove_pointer< typename std::remove_all_extents< TYPE >::type >::type;
    using memPool_t = memPool< uint8_t >;
public:
    /**
     * @brief 构造函数
     */
    objPoolAllocator( ) :pt_pool__( nullptr ){}
    /**
     * @brief 析构函数
     */
    ~objPoolAllocator() = default;
    void setMemPool( std::shared_ptr< memPool_t > pool ){
        pt_pool__ = pool;
    }
    /**
     * @brief 分配内存
     * @param size 内存大小
     * @return void* 内存指针
     */
    type_t * allocate( size_t size ){
        return reinterpret_cast< type_t * >( pt_pool__->malloc( size ).get() );
    }
    /**
     * @brief 释放内存
     * @param p 内存指针
     */
    void deallocate( type_t * p ){
        if( !p ) return;
        std::shared_ptr< uint8_t > ptr( (uint8_t *)p, []( uint8_t * p ){ (void)p;} );
        pt_pool__->free( sizeof( type_t ), ptr );
    }
    private:
        std::shared_ptr< memPool_t > pt_pool__;
};
}